package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping(value = "/list")
    public String list(Model model){
        List<SysUser> list = sysUserService.list();

        model.addAttribute("list",list);

        return "list";
    }
    @PostMapping(value = "add")
    public String add(SysUser sysUser){
        int result = sysUserService.add(sysUser);
        if (result>0){
            return "redirect:/user/list";
        }
        return "toAdd";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){

        return "add";
    }

    @PostMapping(value = "/login")
    public String login(Model model, HttpServletRequest request, String account, String password){

        SysUser sysUser = sysUserService.login(account,password);
        //用户或用户名不正确
        if (sysUser == null){
            model.addAttribute("error","用户或密码不正确");
            return "login";
        }
        request.getSession().setAttribute("userSession",sysUser);
        return "redirect:/user/main";
    }
    @GetMapping(value = "/main")
    public String main(){
        return "frame";
    }
}
